import multer from "multer";
import { JOURNAL_IMG_FOLDER, JOURNAL_IMG_PATH } from "../../config"
import path from "node:path";
import UUidUtil from "../../utils/UUidUtil";
import ResultHelper from "./ResultHelper";
import ResponseHelper from "./ResponseHelper";
import { cutJournalImgHelper } from "./cutJournalImgHelper"

const storage = multer.diskStorage({

  // 保存的路径
  destination: (req, file, cb) => {
    // req.body.dirname = JOURNAL_IMG_PATH;
    cb(null, JOURNAL_IMG_PATH);
  },

  // 保存的文件名
  filename: (req, file, cb) => {

    const ext = path.extname(file.originalname) // 文件后缀
    const uuid = UUidUtil.getUUid()
    const filename = uuid + ext

    req.body.filepaths ?
      req.body.filepaths.push(`/${JOURNAL_IMG_FOLDER}/${filename}`)
      : req.body.filepaths = [`/${JOURNAL_IMG_FOLDER}/${filename}`]

    cb(null, filename)
  },
});

const uploader = multer({ storage: storage }).array("files");

export async function journalImgHelper(req, res) {
  uploader(req, res, async (err) => {
    if (err) {
      const result = err.errno === -4058 ?
        ResultHelper.error("没有journal-img文件夹")
        : ResultHelper.error("上传失败")

      ResponseHelper.sendError(result, res, req)
    } else {

      const filepaths = req.body.filepaths || []
      if (filepaths.length === 0) {
        const result = ResultHelper.error("请选择上传的文件")
        ResponseHelper.sendError(result, res, req)
        return;
      }

      const newFilepaths = filepaths.map((url: string, i: number) => {
        return {
          index: i,
          url,
        }
      })

      // 裁剪 
      for (let i = 0; i < filepaths.length; i++) {
        const filename = req.files[i].filename
        const dirname = req.files[i].destination
        const result = await cutJournalImgHelper(filename, dirname)
        if (result.code === 200) {
          newFilepaths[i].min = result.message
        } else {
          newFilepaths[i].min = filepaths[i]
        }
      }

      const result = ResultHelper.success(newFilepaths, "上传成功")

      ResponseHelper.send(result, res)

    }
  });

}
